package org.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.entity.Permissions;
import org.example.models.R;
import org.example.service.PermissionsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/permissions")
public class PermissionsController {
    @Autowired
    PermissionsService permissionsService;

    @GetMapping("/tree")
    public R getPermissions(@RequestAttribute("userId") Integer userId){
        return R.success(permissionsService.getPermissionTree(0,userId));
    }

    @GetMapping("/roles")
    public R getPermissionsByRoles(Integer userId){
        return R.success(permissionsService.selectByRolesAndUserId(userId));
    }

    @PostMapping
    public R insert(@RequestBody Permissions permissions){
        permissionsService.save(permissions);
        return R.success();
    }

    @PutMapping
    public R update(@RequestBody Permissions permissions){
        permissionsService.updateById(permissions);
        return R.success();
    }

    @DeleteMapping("/{id}")
    public R delete(Integer id){
        permissionsService.removeById(id);
        return R.success();
    }

    @GetMapping("/page")
    public R<Page<Permissions>> page(
            @RequestParam(name="current",defaultValue = "1") int current,
            @RequestParam(name="size",defaultValue = "2") int size,
            @RequestParam(name="zhName",required = false) String zhName
    ) {
        QueryWrapper<Permissions> queryWrapper = new QueryWrapper<>();//查询条件
        if (zhName != null && zhName.length() > 0) {
            queryWrapper.lambda().like(Permissions::getZhName, zhName);
        }
        Page<Permissions> page = new Page<>(current, size);
        permissionsService.page(page, queryWrapper);
        return R.success(page);
    }

}
